import math
import matplotlib.pyplot as plt
import torch
from torch import nn
from torch.nn import functional as F
from d2l import torch as d2l
from data_load_for_rnn import load_data_time_machine

train_iter, vocab = load_data_time_machine(16, 5, True)

for i in train_iter:
    print(i[0].shape)
print("len(vocab)", len(vocab))
# # 索引为 0 1 2 的独热向量
#
# print(F.one_hot(torch.tensor([0, 1, 2]), len(vocab)))
#
# 模拟创建 时间步数=28，批量大小=32，词表大小=1031的输入
X = torch.arange(16 * 5).reshape(16, 5)
print(F.one_hot(X.T, 932).shape)


# words_size,batch_size,vocab_size1


# 8.5.2. 初始化模型参数
def get_params(vocab_size, num_hiddens, device):
    num_inputs = num_outputs = vocab_size

    def normal(shape):
        return torch.randn(size=shape, device=device) * 0.01

    # 隐藏层参数
    # X  n  * d  n 为batch_size , d 在这里指的是词表大小（由于使用了onehot方案，但一般不推荐这种办法。）
    # d * h
    W_xh = normal((num_inputs, num_hiddens))
    # h * h
    W_hh = normal((num_hiddens, num_hiddens))
    b_h = torch.zeros(num_hiddens, device=device)
    # 隐变量 H   n * h
    # 输出层参数 hq  h * q  O size n*q 这里的 q = d
    W_hq = normal((num_hiddens, num_outputs))
    b_q = torch.zeros(num_outputs, device=device)
    # 附加梯度
    params = [W_xh, W_hh, b_h, W_hq, b_q]
    for param in params:
        param.requires_grad_(True)
    return params


# 2、初始化隐藏变量实操 H [32, 512]
def init_rnn_state(batch_size, num_hiddens, device):
    return (torch.zeros((batch_size, num_hiddens), device=device),)


# 6、 循环神经网络的前向计算
def rnn(inputs, state, params):
    # inputs的形状：(时间步数量，批量大小，词表大小)
    W_xh, W_hh, b_h, W_hq, b_q = params
    H, = state
    outputs = []
    # X的形状：(批量大小，词表大小) n*d
    for X in inputs:
        # 8.4.5 公式
        # H (n*d) (d*h)  (n*h) (h*h)
        H = torch.tanh(torch.mm(X, W_xh) + torch.mm(H, W_hh) + b_h)
        # H n*h W_hq h*q
        Y = torch.mm(H, W_hq) + b_q
        # Y = n*q
        # 时间步个 (N*Q) 的向量
        outputs.append(Y)
        # 128 1031
    # 最后得到 T * N * Q(D)的向量
    return torch.cat(outputs, dim=0), (H,)


class RNNModelScratch:  # @save
    """从零开始实现的循环神经网络模型"""

    def __init__(self, vocab_size, num_hiddens, device,
                 get_params, init_state, forward_fn):
        self.vocab_size, self.num_hiddens = vocab_size, num_hiddens
        self.params = get_params(vocab_size, num_hiddens, device)
        self.init_state, self.forward_fn = init_state, forward_fn

    def __call__(self, X, state):
        # 使用onehot的词嵌入方法
        X = F.one_hot(X.T.to(int), self.vocab_size).type(torch.float32)
        return self.forward_fn(X, state, self.params)

    def begin_state(self, batch_size, device):
        return self.init_state(batch_size, self.num_hiddens, device)


num_hiddens = 512
net = RNNModelScratch(len(vocab), num_hiddens, d2l.try_gpu(), get_params,
                      init_rnn_state, rnn)
# 3、隐藏变量  state [n , d] 32,512
state = net.begin_state(X.shape[0], d2l.try_gpu())
# 4、经过rnn网络操作
Y, new_state = net(X.to(d2l.try_gpu()), state)
print("newY new_state", Y.shape, new_state[0].shape)
# # torch.Size([896, 1031]) 1 torch.Size([32, 512])
print(Y.shape, len(new_state), new_state[0].shape)


def predict_ch8(prefix, num_preds, net, vocab, device):  # @save
    """在prefix后面生成新字符"""
    output_list = []
    state = net.begin_state(batch_size=1, device=device)
    outputs = [vocab[prefix]]
    get_input = lambda: torch.tensor([outputs[-1]], device=device).reshape((1, 1))
    # 预热期
    _, state = net(get_input(), state)
    for _ in range(num_preds):  # 预测num_preds步
        y, state = net(get_input(), state)
        arg_max_id = int(y.argmax(dim=1).reshape(1))
        if arg_max_id == vocab["<fin>"]:
            output_list.append(outputs)
            outputs = [vocab[prefix]]
        else:
            outputs.append(arg_max_id)
    new_out_list = []
    for outputs in output_list:
        if ' '.join([vocab.idx_to_token[i] for i in outputs]) not in new_out_list:
            new_out_list.append(' '.join([vocab.idx_to_token[i] for i in outputs]))

    return new_out_list


print("第一次预测", predict_ch8('增加', 10, net, vocab, d2l.try_gpu()))


# 8.5.5. 梯度裁剪
def grad_clipping(net, theta):  # @save
    """裁剪梯度"""
    if isinstance(net, nn.Module):
        params = [p for p in net.parameters() if p.requires_grad]
    else:
        params = net.params
    norm = torch.sqrt(sum(torch.sum((p.grad ** 2)) for p in params))
    if norm > theta:
        for param in params:
            param.grad[:] *= theta / norm


# @save
def train_epoch_ch8(net, train_iter, loss, updater, device, use_random_iter):
    """训练网络一个迭代周期（定义见第8章）"""
    state, timer = None, d2l.Timer()
    metric = d2l.Accumulator(2)  # 训练损失之和,词元数量
    for X, Y in train_iter:
        # print("X.shape [16, 5]",X.shape)
        if state is None or use_random_iter:
            # 在第一次迭代或使用随机抽样时初始化state
            state = net.begin_state(batch_size=X.shape[0], device=device)
        else:
            if isinstance(net, nn.Module) and not isinstance(state, tuple):
                # state对于nn.GRU是个张量
                state.detach_()
            else:
                # state对于nn.LSTM或对于我们从零开始实现的模型是个张量
                for s in state:
                    s.detach_()
        y = Y.T.reshape(-1)
        X, y = X.to(device), y.to(device)

        y_hat, state = net(X, state)
        # print(y_hat.shape,"y_hat",y.shape)
        # torch.Size([80, 932]) y_hat torch.Size([80])
        # 16,5,80 代表16个句子，分别计算交叉熵,得到一个批次的loss损失
        l = loss(y_hat, y.long()).mean()
        # print("l", l)
        if isinstance(updater, torch.optim.Optimizer):
            updater.zero_grad()
            l.backward()
            grad_clipping(net, 1)
            updater.step()
        else:
            l.backward()
            grad_clipping(net, 1)
            # 因为已经调用了mean函数
            updater(batch_size=1)
        # 用16 * 5 个词元的交叉熵作为平均交叉熵乘以y的个数得到
        metric.add(l * y.numel(), y.numel())
    # print(metric[0], metric[1],"metrics")
    # 这里做了两个变更  一个是将2的指数改为了e的指数形式计算
    # 一个是将批次的数据进行累加
    # 其本质不变，仍然是计算交叉熵的加和值并进行运算
    return math.exp(metric[0] / metric[1]), metric[1] / timer.stop()


def train_ch8(net, train_iter, vocab, lr, num_epochs, device,
              use_random_iter=False):
    """训练模型（定义见第8章）"""
    loss = nn.CrossEntropyLoss()
    animator = d2l.Animator(xlabel='epoch', ylabel='perplexity',
                            legend=['train'], xlim=[10, num_epochs])
    # 初始化
    if isinstance(net, nn.Module):
        updater = torch.optim.SGD(net.parameters(), lr)
    else:
        updater = lambda batch_size: d2l.sgd(net.params, lr, batch_size)
    predict = lambda prefix: predict_ch8(prefix, 100, net, vocab, device)
    # 训练和预测
    for epoch in range(num_epochs):
        ppl, speed = train_epoch_ch8(
            net, train_iter, loss, updater, device, use_random_iter)
        if (epoch + 1) % 10 == 0:
            print(predict('物理'))
            animator.add(epoch + 1, [ppl])
    print(f'困惑度 {ppl:.1f}, {speed:.1f} 词元/秒 {str(device)}')
    print(predict('每個'))
    print(predict('每'))


num_epochs, lr = 500, 1
train_ch8(net, train_iter, vocab, lr, num_epochs, d2l.try_gpu())
# train_ch8(net, train_iter, vocab, lr, num_epochs, d2l.try_gpu(), use_random_iter=False)
plt.show()
